<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息收集</h2>
          <p class="subtitle">请填写您的身体指标和健身目标，我们将为您生成个性化的饮食计划</p>
        </div>
      </template>

      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="120px"
        class="profile-form"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">
          <h3>基本信息</h3>
        </el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname" placeholder="请输入您的昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="profileForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="M" />
                <el-option label="女" value="F" />
                <el-option label="其他" value="O" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="出生日期" prop="birth_date">
          <el-date-picker
            v-model="profileForm.birth_date"
            type="date"
            placeholder="请选择出生日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <!-- 身体指标 -->
        <el-divider content-position="left">
          <h3>身体指标</h3>
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number
                v-model="profileForm.height"
                :min="50"
                :max="250"
                :precision="1"
                style="width: 100%"
                placeholder="请输入身高"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number
                v-model="profileForm.weight"
                :min="20"
                :max="300"
                :precision="1"
                style="width: 100%"
                placeholder="请输入体重"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- BMI显示 -->
        <el-form-item v-if="bmiInfo.bmi" label="BMI指数">
          <el-tag :type="bmiInfo.type" size="large">
            {{ bmiInfo.bmi }} - {{ bmiInfo.category }}
          </el-tag>
        </el-form-item>

        <!-- 健身目标 -->
        <el-divider content-position="left">
          <h3>健身目标</h3>
        </el-divider>

        <el-form-item label="健身目标" prop="fitness_goal">
          <el-radio-group v-model="profileForm.fitness_goal">
            <el-radio label="weight_loss">减脂</el-radio>
            <el-radio label="muscle_gain">增肌</el-radio>
            <el-radio label="keep_fit">保持健康</el-radio>
            <el-radio label="endurance">提升耐力</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="健身水平" prop="fitness_level">
          <el-radio-group v-model="profileForm.fitness_level">
            <el-radio label="beginner">新手</el-radio>
            <el-radio label="intermediate">进阶</el-radio>
            <el-radio label="advanced">专业</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="活动水平" prop="activity_level">
          <el-select v-model="profileForm.activity_level" placeholder="请选择活动水平" style="width: 100%">
            <el-option label="久坐(几乎不运动)" value="sedentary" />
            <el-option label="轻度活动(每周1-3天运动)" value="light" />
            <el-option label="中度活动(每周3-5天运动)" value="moderate" />
            <el-option label="积极活动(每周6-7天运动)" value="active" />
            <el-option label="非常活跃(高强度训练或体力工作)" value="very_active" />
          </el-select>
        </el-form-item>

        <!-- 饮食偏好 -->
        <el-divider content-position="left">
          <h3>饮食偏好</h3>
        </el-divider>

        <el-form-item label="饮食偏好" prop="dietary_preference">
          <el-select v-model="profileForm.dietary_preference" placeholder="请选择饮食偏好" style="width: 100%">
            <el-option label="普通" value="regular" />
            <el-option label="素食" value="vegetarian" />
            <el-option label="纯素" value="vegan" />
            <el-option label="低碳水" value="low_carb" />
            <el-option label="生酮" value="keto" />
            <el-option label="无麸质" value="gluten_free" />
            <el-option label="无乳糖" value="lactose_free" />
          </el-select>
        </el-form-item>

        <el-form-item label="食物过敏" prop="food_allergies">
          <el-input
            v-model="profileForm.food_allergies"
            type="textarea"
            :rows="3"
            placeholder="请描述您的食物过敏情况（如有）"
          />
        </el-form-item>

        <el-form-item label="其他饮食限制" prop="dietary_restrictions">
          <el-input
            v-model="profileForm.dietary_restrictions"
            type="textarea"
            :rows="3"
            placeholder="请描述其他饮食限制（如有）"
          />
        </el-form-item>

        <!-- 健康信息 -->
        <el-divider content-position="left">
          <h3>健康信息</h3>
        </el-divider>

        <el-form-item label="健康状况">
          <el-checkbox-group v-model="healthConditions">
            <el-checkbox label="diabetes">糖尿病</el-checkbox>
            <el-checkbox label="hypertension">高血压</el-checkbox>
            <el-checkbox label="heart_disease">心脏病</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 健身偏好 -->
        <el-divider content-position="left">
          <h3>健身偏好</h3>
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单次训练时长(分钟)" prop="preferred_workout_duration">
              <el-input-number
                v-model="profileForm.preferred_workout_duration"
                :min="10"
                :max="180"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每周训练次数" prop="preferred_workout_times">
              <el-input-number
                v-model="profileForm.preferred_workout_times"
                :min="1"
                :max="7"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitProfile" :loading="loading" size="large">
            保存信息
          </el-button>
          <el-button @click="resetForm" size="large">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { dietAPI } from '@/api/index'

const profileFormRef = ref()
const loading = ref(false)

// 表单数据
const profileForm = reactive({
  nickname: '',
  gender: '',
  birth_date: '',
  height: null,
  weight: null,
  fitness_goal: 'keep_fit',
  fitness_level: 'beginner',
  activity_level: 'sedentary',
  dietary_preference: 'regular',
  food_allergies: '',
  dietary_restrictions: '',
  preferred_workout_duration: 30,
  preferred_workout_times: 3
})

// 健康状况
const healthConditions = ref([])

// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birth_date: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' }
  ],
  fitness_goal: [
    { required: true, message: '请选择健身目标', trigger: 'change' }
  ],
  fitness_level: [
    { required: true, message: '请选择健身水平', trigger: 'change' }
  ],
  activity_level: [
    { required: true, message: '请选择活动水平', trigger: 'change' }
  ],
  dietary_preference: [
    { required: true, message: '请选择饮食偏好', trigger: 'change' }
  ]
}

// 计算BMI信息
const bmiInfo = computed(() => {
  if (!profileForm.height || !profileForm.weight) {
    return { bmi: null, category: '', type: '' }
  }

  const heightInM = profileForm.height / 100
  const bmi = (profileForm.weight / (heightInM * heightInM)).toFixed(1)
  
  let category = ''
  let type = ''
  
  if (bmi < 18.5) {
    category = '偏瘦'
    type = 'warning'
  } else if (bmi < 25) {
    category = '正常'
    type = 'success'
  } else if (bmi < 30) {
    category = '超重'
    type = 'warning'
  } else {
    category = '肥胖'
    type = 'danger'
  }

  return { bmi, category, type }
})

// 获取用户档案信息
const getUserProfile = async () => {
  try {
    const response = await dietAPI.getUserProfile()
    if (response) {
      // 填充表单数据
      Object.assign(profileForm, response)
      
      // 设置健康状况
      healthConditions.value = []
      if (response.has_diabetes) healthConditions.value.push('diabetes')
      if (response.has_hypertension) healthConditions.value.push('hypertension')
      if (response.has_heart_disease) healthConditions.value.push('heart_disease')
    }
  } catch (error) {
    console.error('获取用户档案失败:', error)
  }
}

// 提交表单
const submitProfile = async () => {
  try {
    await profileFormRef.value.validate()
    
    loading.value = true
    
    // 处理健康状况
    const formData = {
      ...profileForm,
      has_diabetes: healthConditions.value.includes('diabetes'),
      has_hypertension: healthConditions.value.includes('hypertension'),
      has_heart_disease: healthConditions.value.includes('heart_disease')
    }
    
    const response = await dietAPI.updateUserProfile(formData)
    
    if (response) {
      ElMessage.success('个人信息保存成功！')
    }
  } catch (error) {
    console.error('保存个人信息失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  profileFormRef.value.resetFields()
  healthConditions.value = []
}

// 组件挂载时获取用户档案
onMounted(() => {
  getUserProfile()
})
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
}

.subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.profile-form {
  margin-top: 20px;
}

.el-divider h3 {
  margin: 0;
  color: #409eff;
  font-size: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }
  
  .profile-card {
    margin: 0;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
}
</style>
